package nbcp.web.sys

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import nbcp.base.comm.*
import nbcp.base.extend.*
import nbcp.base.utf8
import nbcp.base.utils.ImageUtil
import nbcp.comm.JsonpMapping
import nbcp.db.IdName
import nbcp.db.IdUrl
import nbcp.model.IdUrlMsg
import nbcp.service.UploadService
import nbcp.web.MyHttpRequestWrapper
import nbcp.web.UserId
import nbcp.web.UserName
import nbcp.web.WriteJsonRawValue
import springfox.documentation.annotations.ApiIgnore
import java.io.File
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by udi on 17-4-12.
 */


/**
 * 客户端上传流程：
 *  1. 客户端调用 /sys/check_upload 方法，判断服务器是否有该文件，有则返回文件Id，没有返回空字符串表示客户端需要上传。
 *  2. 如果需要上传，客户端调用 /sys/upload 方法，返回文件Id
 *  3. 客户端调用 业务方法，把文件Id和业务关联。
 */

@RestController
class FileUpload_Controller {

//    @Value("\${shop.uploadServer.host}")
//    var imgHost: String = "";

    @Autowired
    lateinit var uploadService: UploadService;

    /**
     * 文件上传流程：
     *  1. 保存文件
     *  2. 计算文件 Md5 值
     *  3. 插入到 SysAnnex 表中。
     *  4. 返回 SysAnnex.id
     */
    @ApiOperation("文件上传", notes = """
客户端Content-Type：
Content-Type: multipart/form-data; boundary=----xxxx
请求FormData的内容：
------xxxx
Content-Disposition: form-data; name="用户管理（包含描述）.xlsx"; filename="blob"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

xxxxxxxx
------xxxx--
""", tags = arrayOf("file"))
    @PostMapping("/sys/upload")
    fun fileUpload(request: HttpServletRequest, response: HttpServletResponse) {

        var session = request;
//        if (session.CorpId.isNullOrBlank() && !request.IsProxy) {
//            response.WriteJsonRawValue(JsonResult("需要您登录").ToJson());
//            return;
//        }

        var ret = uploadService.upload(request, IdName(request.UserId, request.UserName),request.Corp.id) { fileName, extType ->
            if (extType == FileExtentionTypeEnum.Image) {
                ImageUtil.zoomImageScale(fileName, fileName, 1440, 1440)
            }
        };

        if (ret.msg.HasValue) {
            response.WriteJsonRawValue(JsonResult(ret.msg).ToJson())
            return;
        }

        var ids = ret.data;

        response.contentType = "application/json;charset=UTF-8"
        if (ids.size == 0) {
            response.outputStream.write(JsonResult("上传失败").ToJson().toByteArray(utf8));
        } else if (ids.size == 1) {
            response.outputStream.write(ApiResult.of(IdUrl(ids[0].id, ids[0].url)).ToJson().toByteArray(utf8));
        } else {
            response.outputStream.write(ListResult.of(ids).ToJson().toByteArray(utf8));
        }
        return
    }


    //没用. 请使用 fileCheckUpload
//    @JsonpMapping("/sys/fileCheck")
//    fun fileCheck(md5: String, request: HttpServletRequest): JsonResult {
//        return ApiResult(data = mor.system.sysAnnex.query(mor.system.sysAnnex.checkCode match md5).exists())//"checkCode"
//    }

    @ApiIgnore
    //如果存在，返回 id  url
    @JsonpMapping("/sys/check_upload")
    fun fileCheckUpload(md5: String, request: HttpServletRequest): IdUrlMsg {
        var ret = uploadService.onFileMd5Check(md5, IdName(request.UserId, request.UserName), request.Corp.id);

        return ret;
    }
}
